
from PIL import Image
import numpy as np
from os import path
import os
import struct
import re

def image2bin(input, output = None):
    if not output:
        output = re.sub("[ \\+\\-\\(\\)\\[\\]\\.]","_",path.split(input)[-1])+".bin"
    img = Image.open(input)
    cf = None
    w = img.size[0]
    h = img.size[1]
    if img.mode == "RGBA":
        cf = 5
    elif img.mode == "RGB":
        cf = 4
    header = (cf & (2**5-1)) | ((w & (2**11-1))<<10) | ((h & (2**11-1))<<21)
    
    pixle = np.array(img)
    pixle_color = pixle[:,:,0:3]
    pixle_alpha = None
    if img.mode == "RGBA":
        pixle_alpha = pixle[:,:,3]
    tmp = pixle_color.astype(np.uint16)
    r = tmp[:,:,0]
    g = tmp[:,:,1]
    b = tmp[:,:,2]
    tmp2 = ((r << 8) & 0xf800)|((g << 3) & 0x07E0)|((b >> 3) & 0x001F)
    # tmp2  = (((tmp[:,:,0] >> 3)& (2**5-1))<< 11)|(((tmp[:,:,0] >> 2)& (2**6-1))<< 5)|(((tmp[:,:,0] >> 3)& (2**5-1))<< 0)
    
    pixle_color_words = (tmp2 >> 8 | tmp2 << 8)
    pixle_color_words.shape = (pixle_color_words.shape[0]*pixle_color_words.shape[1],)
    
    f = open(output, "wb")
    if img.mode == "RGBA":
        pixle_alpha.shape = (pixle_alpha.shape[0]*pixle_alpha.shape[1],)
        f.write(struct.pack("<I", header))
        for color, alpha in zip(pixle_color_words,pixle_alpha) :
            f.write(struct.pack("<HB", color, alpha))
    elif img.mode == "RGB":
        f.write(struct.pack("<I", header))
        for raw in pixle_color_words:
            f.write(struct.pack("<H", raw))
    f.close()
if __name__ == "__main__":
    files_list = os.listdir("./picture")
    ext_support = (".jpg", ".bmp", ".png")
    for name in files_list:
        ext = path.splitext(path.split(name)[-1])[-1]
        if ext in ext_support:
            image2bin(name)
    merge_all_bin()
    